<?php

namespace app\common\service\haikang;

use app\common\model\haikang\HkConsumerMsg;
use think\facade\Env;
use think\facade\Queue;

/**
 * 海康相关服务
 */
class HaikangService
{
    /**
     * 获取海康accessToken
     * @return mixed|object|\think\App
     */
    public static function accessToken()
    {
        $access_token = cache("haikang_access_token");
        if (empty($access_token)) {
            $url = 'https://api2.hik-cloud.com/oauth/token';
            $http_post = http_post($url, [
                'client_id' => Env::get('Haikang.client_id'),
                'client_secret' => Env::get('Haikang.client_secret'),
                'grant_type' => 'client_credentials',
            ]);
            $access_token = json_decode($http_post, true);
            cache("haikang_access_token", $access_token, $access_token['expires_in'] - 100);
        }
        return $access_token;
    }

    /**
     * 海康获取视频取流时需要的认证信息
     * @return array
     */
    public static function ezvizAccountInfo():array
    {
        $access_token = self::accessToken();
        $url = 'https://api2.hik-cloud.com/v1/ezviz/account/info';
        $messages = httpGet($url, 'Authorization: Bearer' . $access_token['access_token']);
        $messages = json_decode($messages, true);
        return $messages['data'] ?? [];
    }

    /**
     * 创建消费者consumerId
     * @return mixed|object|\think\App
     */
    public static function createConsumerId()
    {
        $cache_name = 'createConsumerId';
        $consumer = cache($cache_name);
        if (empty($consumer)) {
            $access_token = self::accessToken();
            $url = 'https://api2.hik-cloud.com/api/v1/mq/consumer/group1';
            $res = http_post($url, [
                'consumerId' => md5(time())
            ], 'Authorization: Bearer' . $access_token['access_token']);
            $consumer = json_decode($res, true);
            cache($cache_name, $consumer, 290);
        }
        return $consumer;
    }

    /**
     * 获取摄像头捕捉数据
     * @return array
     */
    public static function getMessages()
    {
        $access_token = self::accessToken();
        $url = 'https://api2.hik-cloud.com/api/v1/mq/consumer/messages';
        $consumerId = self::createConsumerId();
        $messages = http_post($url, [
            'consumerId' => $consumerId['data']['consumerId'],
            'autoCommit' => "true"
        ], 'Authorization: Bearer' . $access_token['access_token']);
        $messages = json_decode($messages, true);
        return [
            'messages' => $messages,
            'consumerId' => $consumerId['data']['consumerId'],
        ];
    }

    /**
     * 把网络图片下载到本地
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function setServerImgUrl()
    {
        $hk_consumer_msg = HkConsumerMsg::where('server_img_url', null)
            ->where('image_url', 'not null')
            ->field('id,image_url,msg_id')
            ->limit(300)
            ->select()
            ->toArray();
        if (!empty($hk_consumer_msg)) {
            foreach ($hk_consumer_msg as $val) {
                if (empty($val['image_url'])) continue;
                // 1.当前任务将由哪个类来负责处理。
                $jobHandlerClassName = 'app\queue\haikang\SetServerImgUrlQueue';
                // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                $jobQueueName = "SetServerImgUrlQueue"; //php think queue:listen --queue SetServerImgUrlQueue
                Queue::push($jobHandlerClassName, $val, $jobQueueName);
            }
        }
    }
}